package com.example.oss.controller;

import com.example.oss.annotation.LoginLimit;
import com.example.oss.annotation.OperationLog;
import com.example.oss.entity.Result;
import com.example.oss.entity.ResultEnum;
import com.example.oss.entity.Student;
import com.example.oss.service.StudentService;
import com.google.common.base.Strings;
import com.wf.captcha.utils.CaptchaUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

@Controller
@Slf4j
@RequiredArgsConstructor
public class LoginController {


    private final StudentService studentService;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.expiration}")
    private int expiration;

    @Value("${server.servlet.context-path}")
    private String contextPath;


    @OperationLog("请求验证码")
    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        CaptchaUtil.out(request, response);
    }

    @OperationLog("跳转到登录页面")
    @GetMapping("/toLogin")
    public String toLogin() {
        return "login";
    }


    @OperationLog("用户登录")
    //4秒内最多点击一次
    @LoginLimit(second = 4, maxCount = 1)
    @PostMapping("/doLogin")
    @ResponseBody
    public Result doLogin(@Valid Student student, @Valid @NotBlank(message = "验证码不能为空！") String verifyCode,
                          HttpServletRequest request, HttpServletResponse response) {

        if (!CaptchaUtil.ver(verifyCode, request)) {
            return Result.failure(ResultEnum.VERIFY_CODE_ERROR);
        }

        Result res = studentService.login(student);
        if (!Strings.isNullOrEmpty(res.getToken())) {
            Cookie cookie = new Cookie(tokenHeader, res.getToken());
            cookie.setPath(contextPath);
            cookie.setMaxAge(expiration);
            response.addCookie(cookie);
        }
        return res;
    }


    @OperationLog("退出登录")
    @GetMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        //删除浏览器Cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(tokenHeader)) {
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                    break;
                }
            }
        }
        return "redirect:/toLogin";
    }

}
